package com.fingard.dsp.bank.directbank.zjrc01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ZJRC01Transaction extends ZJRC01Base implements ITransaction {

    //采用流处理方式
    //1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用writeRetDetail()，写入返回ATS的明细
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            tranCode = "200002";
            serialNo = p_req7516.reqHeader.transSeqID;
            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpNowStartRecord = 0;//总条数
            int intPageNumber = 1;//页码数 默认查询第一页
            int tmpNowReadedCount = 0;//已读条数

            boolean tmpQryNext = true;
            while (tmpQryNext && tmpRespCode.length() == 0) {//分页查询
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter);
                xmlWriter.writeElementString("accountNo", p_req7516.actNum);
                xmlWriter.writeElementString("currencyType", convertCurToBank(p_req7516.actCur));
                xmlWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpCalendarTo.getTime()));
                xmlWriter.writeElementString("page", String.valueOf(intPageNumber));
                xmlWriter.writeElementString("showNum", "50");//可以为空，默认50条，最大200条
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                //模拟银行返回
                /*tmpStrRet[0]="";
                tmpStrRet[1]="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                        "<ebank>\n" +
                        "\t<resHead>\n" +
                        "\t\t<retCode>0000</retCode>\n" +
                        "\t\t<errMsg>返回错误信息</errMsg>\n" +
                        "\t\t<serialNo>12345678</serialNo>\n" +
                        "\t</resHead>\n" +
                        "\t<resBody>\n" +
                        "\t\t<page>1</page>\n" +
                        "\t\t<totalNum>2</totalNum>\n" +
                        "\t\t<transDetailList>\n" +
                        "\t\t\t<row>\n" +
                        "\t\t\t\t<accountNo>123456</accountNo>\n" +
                        "\t\t\t\t<transferDate>20170619</transferDate>\n" +
                        "\t\t\t\t<transferFlowNo>20170619</transferFlowNo>\n" +
                        "\t\t\t\t<subTranFlow>123456</subTranFlow>\n" +
                        "\t\t\t\t<currencyType>CNY</currencyType>\n" +
                        "\t\t\t\t<cashFlag>1</cashFlag>\n" +
                        "\t\t\t\t<loanFlag>1</loanFlag>\n" +
                        "\t\t\t\t<transferSum>26.11</transferSum>\n" +
                        "\t\t\t\t<balance>19666.22</balance>\n" +
                        "\t\t\t\t<vouchersNo></vouchersNo>\n" +
                        "\t\t\t\t<otherAccNo>456789</otherAccNo>\n" +
                        "\t\t\t\t<recAccountName>对方户名</recAccountName>\n" +
                        "\t\t\t\t<recAccountOpenBank>收款方开户行</recAccountOpenBank>\n" +
                        "\t\t\t\t<transferTime>2017-06-19 10.50.20.666</transferTime>\n" +
                        "\t\t\t\t<tranChannel>交易渠道</tranChannel>\n" +
                        "\t\t\t\t<remark>用途</remark>\n" +
                        "\t\t\t</row>\n" +
                        "\t\t\t<row>\n" +
                        "\t\t\t\t<accountNo>123456</accountNo>\n" +
                        "\t\t\t\t<transferDate>20170619</transferDate>\n" +
                        "\t\t\t\t<transferFlowNo>20170619</transferFlowNo>\n" +
                        "\t\t\t\t<subTranFlow>123456</subTranFlow>\n" +
                        "\t\t\t\t<currencyType>CNY</currencyType>\n" +
                        "\t\t\t\t<cashFlag>1</cashFlag>\n" +
                        "\t\t\t\t<loanFlag>2</loanFlag>\n" +
                        "\t\t\t\t<transferSum>24.11</transferSum>\n" +
                        "\t\t\t\t<balance>19646.22</balance>\n" +
                        "\t\t\t\t<vouchersNo></vouchersNo>\n" +
                        "\t\t\t\t<otherAccNo>456789</otherAccNo>\n" +
                        "\t\t\t\t<recAccountName>对方户名</recAccountName>\n" +
                        "\t\t\t\t<recAccountOpenBank>收款方开户行</recAccountOpenBank>\n" +
                        "\t\t\t\t<transferTime>2017-06-19 10.50.20.666</transferTime>\n" +
                        "\t\t\t\t<tranChannel>交易渠道</tranChannel>\n" +
                        "\t\t\t\t<remark>用途</remark>\n" +
                        "\t\t\t</row>\n" +
                        "\t\t</transDetailList>\n" +
                        "\t</resBody>\n" +
                        "</ebank>\n";*/
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    int index = tmpStrRet[1].indexOf("</ebank>");
                    tmpStrRet[1] = tmpStrRet[1].substring(0, index + 8);
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/ebank/resHead/retCode");
                        String returnMsg = tmpBkReader.getFirstText("/ebank/resHead/errMsg");
                        if (isActiveRetCode(returnCode)) {
                            int tmpTotalRocords = 0;//总条数
                            int nowPage = 0;//当前页码
                            nowPage = Integer.parseInt(tmpBkReader.getFirstText("/ebank/resBody/page"));
                            if (tmpBkReader.getFirstText("/ebank/resBody/totalNumber") != null && tmpBkReader.getFirstText("/ebank/resBody/totalNumber").trim().length() > 0) {
                                tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/ebank/resBody/totalNumber"));
                            }
                            int tmpEachPiCount = 0;
                            while (tmpBkReader.read("/ebank/resBody/transDetailList/row")) {
                                tmpEachPiCount++;
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("accountNo");
                                tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("recAccountOpenBank");
                                tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("otherAccNo");
                                tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("recAccountName");
                                tmpRetDetail.cur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("currencyType"));
                                String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("loanFlag");//1-借或表外收、2-贷或表外付
                                String tranAmount = tmpBkReader.readedXElement.getSingleText("transferSum");
                                if (creditDebitFlag != null) {
                                    if (creditDebitFlag.equals("1")) // 原先是D 借贷标识
                                    {
                                        if (tranAmount.indexOf("-") >= 0) {
                                            tmpRetDetail.cdFlag = "2";
                                        } else {
                                            tmpRetDetail.cdFlag = "1";
                                        }
                                    } else if (creditDebitFlag.equals("2")) {
                                        if (tranAmount.indexOf("-") >= 0) {
                                            tmpRetDetail.cdFlag = "1";
                                        } else {
                                            tmpRetDetail.cdFlag = "2";
                                        }
                                    } else {
                                        WriteBankLogLn("借贷标志( " + creditDebitFlag + ")无法识别，说明为新开户账号");
                                        continue;
                                        /*tmpRespCode = "-1";
                                        tmpRespInfo = "借贷标志( "+ creditDebitFlag+ ")无法识别，请与银行核对";
                                        retAts = new RetAtsTrans(p_req7516.reqHeader);
                                        retAts.writeStart();//写返回ATS的统一头部信息
                                        retAts.writeRespCode(tmpRespCode);
                                        retAts.writeRespInfo(tmpRespInfo);
                                        retAts.writeEnd();
                                        return retAts;*/
                                    }
                                }
                                tmpRetDetail.tranAmt = tranAmount.replace("-", "");
                                tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance").trim();//余额

                                String tranDate = tmpBkReader.readedXElement.getSingleText("transferTime");//yyyy-MM-dd hh.mm.ss.SSS交易时间 26位 未知格式  系统格式为yyyy-MM-dd hh:mm:ss
                                tmpRetDetail.tranDate = tranDate.substring(0, 10);
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranDate.substring(11, 19).replace(".", ":");
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;////起息日没有返回就用交易日
                                tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("remark");
                                tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
                                    tmpRetDetail.actNum = p_req7516.actNum;
                                }
                                //业务参考号与银行流水号用于回单匹配
                                tmpRetDetail.bnkSeqNo = tmpBkReader.readedXElement.getSingleText("transferTellerNo") +
                                        tmpBkReader.readedXElement.getSingleText("tellerFlow") +
                                        tmpBkReader.readedXElement.getSingleText("subTranFlow") + DateHelper.convertD10toD8(tmpRetDetail.tranDate);
                                tmpRetDetail.busRef = tmpBkReader.readedXElement.getSingleText("transferFlowNo") +
                                        tmpBkReader.readedXElement.getSingleText("subTranFlow") + DateHelper.convertD10toD8(tmpRetDetail.tranDate);
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                            tmpNowReadedCount += tmpEachPiCount;//总记录数
                            //这个判断逻辑不对吧
                            /*if (tmpEachPiCount != tmpTotalRocords) {
                                tmpQryNext = false;
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行预期返回" + tmpTotalRocords + "条，实际读取" + tmpEachPiCount + "条";
                                break;
                            }*/
                            if (nowPage != intPageNumber) {
                                tmpQryNext = false;
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行返回当前页码为第" + nowPage + "页，实际读取查询页码为第" + intPageNumber + "页";
                                break;
                            }
                            if (tmpNowReadedCount < tmpTotalRocords)//查询下一页
                            {
                                intPageNumber = intPageNumber + 1;//页码加一 查询第二页
                                tmpNowStartRecord = tmpNowReadedCount + 1;//记录已经查询的记录个数
                            } else if (tmpNowReadedCount == tmpTotalRocords)//本次分页查询完毕
                            {
                                tmpQryNext = false;
                                tmpNowStartRecord = 0;
                                tmpNowReadedCount = 0;
                                continue;
                            }
                        } else {
                            tmpQryNext = false;
                            tmpRespCode = "-1";
                            tmpRespInfo = returnMsg;
                            break;
                        }
                    } else {
                        tmpQryNext = false;
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpQryNext = false;
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
